<?php
/**
 * @link http://www.tpframe.com/
 * @copyright Copyright (c) 2017 TPFrame Software LLC
 * @author 510974211@qq.com
 */
namespace tpfcore\loginsdk;
use tpfcore\base\SdkOauth;
class WxgzhSDK extends SdkOauth{

	/**
	 * 获取requestCode的api接口
	 * @var string
	 */
	protected $GetRequestCodeURL = 'https://graph.qq.com/oauth2.0/authorize';
	
	/**
	 * 获取access_token的api接口
	 * @var string
	 */
	protected $GetAccessTokenURL = 'https://graph.qq.com/oauth2.0/token';
	
	/**
	 * 获取request_code的额外参数,可在配置中修改 URL查询字符串格式
	 * @var srting
	 */
	protected $Authorize = 'scope=get_user_info,add_share';

	/**
	 * API根路径
	 * @var string
	 */
	protected $ApiBase = 'https://graph.qq.com/';

	/**
	 * 组装接口调用参数 并调用接口
	 * @param  string $api    微博API
	 * @param  string $param  调用API的额外参数
	 * @param  string $method HTTP请求方法 默认为GET
	 * @return json
	 */
	public function call($api, $param = '', $method = 'GET', $multi = false){
		/* 腾讯QQ调用公共参数 */
		$params = array(
			'oauth_consumer_key' => $this->AppKey,
			'access_token'       => $this->Token['access_token'],
			'openid'             => $this->openid(),
			'format'             => 'json'
		);
		$data = $this->http($this->url($api), $this->param($params, $param), $method);
		return json_decode($data, true);
	}
	
	/**
	 * 解析access_token方法请求后的返回值 
	 * @param string $result 获取access_token的方法的返回值
	 */
	protected function parseToken($result, $extend){
		parse_str($result, $data);
		if($data['access_token'] && $data['expires_in']){
			$this->Token    = $data;
			$data['openid'] = $this->openid();
			return $data;
		} else
			throw new \Exception("获取腾讯QQ ACCESS_TOKEN 出错：{$result}");
	}
	
	/**
	 * 获取当前授权应用的openid
	 * @return string
	 */
	public function openid(){
		$data = $this->Token;
		if(isset($data['openid']))
			return $data['openid'];
		elseif($data['access_token']){
			$data = $this->http($this->url('oauth2.0/me'), array('access_token' => $data['access_token']));
			$data = json_decode(trim(substr($data, 9), " );\n"), true);
			if(isset($data['openid']))
				return $data['openid'];
			else
				throw new \Exception("获取用户openid出错：{$data['error_description']}");
		} else {
			throw new \Exception('没有获取到openid！');
		}
	}
	/**
	 * 获取当前授权用户的基本信息
	 * @return string
	 */
	public function get_user_info(){
		$data=$this->call('user/get_user_info');
		if(isset($data['ret']) && $data['ret'] == 0)
			return $data;
		else
			throw new \Exception("获取用户基本信息出错：{$data['msg']}");
		
	}
	public function getMpAccessToken(){
		$param=[
			'appid'=>$this->AppKey,
			'secret'=>$this->AppSecret,
			'grant_type'=>'client_credential'
		];
		$data=$this->http("https://api.weixin.qq.com/cgi-bin/token",$param);
		return json_decode($data,true);
	}
	/*
		{"subscribe":1,"openid":"oYY5c0qMrRe6OEH1n2KKqiFgpZd4","nickname":"。。。。。","sex":1,"language":"zh_CN","city":"江北","province":"重庆","country":"中国","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/q5f4GTqHsicqQJxJ2YPqPl7QxwBpsmy5qqicDgrpFFPbo9ibVG9kXY1ayEE6y0hiaQ0tgj9BNwHwxjjH8v6Vw60wdMj7CaWZQPvU\/0","subscribe_time":1504258410,"remark":"","groupid":0,"tagid_list":[]}
	*/
	public function getUserInfo($ACCESS_TOKEN,$openid){
		$param=[
			'access_token'=>$ACCESS_TOKEN,
			'openid'=>$openid
		];
		$data=$this->http("https://api.weixin.qq.com/cgi-bin/user/info",$param);

		return json_decode($data,true);
	}

	/**
     * 
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url，需要url编码
     * 
     * @return 返回构造好的url
     */
    public function __CreateOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = $this->AppKey;
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_base";
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }
    /**
     * 
     * 拼接签名字符串
     * @param array $urlObj
     * 
     * @return 返回已经拼接好的字符串
     */
    public function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }
        
        $buff = trim($buff, "&");
        return $buff;
    }
    /**
     * 
     * 通过code从工作平台获取openid机器access_token
     * @param string $code 微信跳转回来带上的code
     * 
     * @return openid
     */
    public function GetOpenidFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);
        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        /*if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0" 
            && WxPayConfig::CURL_PROXY_PORT != 0){
            curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
            curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
        }*/
        //运行curl，结果以jason形式返回
        $res = curl_exec($ch);
        curl_close($ch);
        //取出openid
        $data = json_decode($res,true);
        if(isset($data['errmsg'])){throw new Exception($data['errmsg']);}
        $this->data = $data;
        $openid = $data['openid'];
        return $openid;
    }
    /**
     * 
     * 构造获取open和access_toke的url地址
     * @param string $code，微信跳转带回的code
     * 
     * @return 请求的url
     */
    public function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = $this->AppKey;
        $urlObj["secret"] = $this->AppSecret;
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }
}
/*
	if(!Session::has('user') && strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false){
            $return_url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'];   // 完整Url
            Session::set("before_url",$return_url);
            $WxgzhSDK=SdkOauth::getInstance("Wxgzh",['APP_KEY'=>'wx141ace6be0284b0b','APP_SECRET'=>'218c74ebeb126617b7391c673738f2fd']);
            if (!isset($_GET['code'])){
                //触发微信返回code码
                $baseUrl = urlencode($return_url);
                $url = $WxgzhSDK->__CreateOauthUrlForCode($baseUrl);
                Header("Location: $url");
                exit();
            } else {
                //获取code码，以获取openid
                $code = $_GET['code'];

                $openid = $WxgzhSDK->getOpenidFromMp($code);

                $listUser=Core::loadModel("User")->getUser(['openid'=>$openid]);

                $lastid=$listUser['id'];
                $nickname=$listUser['nickname'];
                $headimg=$listUser['headimg'];

                // 得到openid后存入数据库
                if(count($listUser)==0){    
                    // 没有该用户就添加用户
                    $result=$WxgzhSDK->getMpAccessToken();  //  然后获取全局Access Token

                    $userinfo=$WxgzhSDK->getUserInfo($result['access_token'],$openid);
                    $data['openid']=$userinfo['openid'];
                    $nickname=$data['nickname']=isset($userinfo['nickname'])?$userinfo['nickname']:"爱心购";
                    $data['gender']=isset($userinfo['sex'])?$userinfo['sex']:1;
                    $headimg=$data['headimg']=isset($userinfo['headimgurl'])?$userinfo['headimgurl']:"";

                    $lastid=Core::loadModel("User")->addUser($data);

                }

                Session::set("user",['id'=>$lastid,"nickname"=>$nickname,'headimg'=>$headimg]);
                
                // 跳转至授权前的页面
                $this->redirect(Session::get("before_url"));exit;
            } 
        }
    }
*/